﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using intelliSys.Management.Automation.Profiler.Properties;
using System.Threading;

namespace intelliSys.Management.Automation.Profiler
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static bool IsSqlDBAttached;
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            InvokeRestoration();
        }
        public static void InvokeRestoration()
        {
            Settings.Default.UseSQL = true;
            Settings.Default.Save();
            OfflineTask.AddOfflineTask(OfflineTask.OfflineTaskType.DBMigration);
            UnhandledException ue = new UnhandledException();
            ue.Show();
        }
        public void Application_Exit(object sender, ExitEventArgs e)
        {
            if (Settings.Default.UseSQL != IsSqlDBAttached)
            {
                OfflineTask.AddOfflineTask(OfflineTask.OfflineTaskType.DBMigration);
            }
            OfflineTask.ExecuteAll();
            oneInstanceLock.ReleaseMutex();
            oneInstanceLock.Dispose();
        }
        Mutex oneInstanceLock;
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            IsSqlDBAttached = Settings.Default.UseSQL;
            bool Start = false;
            try
            {
                oneInstanceLock = Mutex.OpenExisting("intelliSysTestProfiler");
                Start = false;
            }
            catch (Exception)
            {
                oneInstanceLock = new Mutex(true, "intelliSysTestProfiler", out Start);
            }
            if (!Start)
            {
                MessageBox.Show("Only one instance is allowed at one time", "intelliSys Test Automation eXplorer");
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }
    }
}
